"use strict";

var React = require("react");
var AuthorStore = require("../../stores/authorStore");
var AuthorList = require("./authorList");
var Router = require("react-router");
var AuthorActions = require("../../actions/authorActions");
var toastr = require("toastr");

var Link = Router.Link;

var AuthorPage = React.createClass({
    getInitialState: function () {
        return {
            authors: []
        };
    },
    componentDidMount: function () {
        if (this.isMounted()) {
            this.setState({authors: AuthorStore.getAllAuthors()});

        }
    },

    componentWillMount: function () {
        AuthorStore.addChangeListener(this._onChange);
    },

    componentWillUnmount: function () {
        AuthorStore.removeChangeListener(this._onChange);
    },

    _onChange: function () {
        this.setState({authors: AuthorStore.getAllAuthors()});
    },

    deleteAuthor: function (id, event) {
        event.preventDefault();
        AuthorActions.deleteAuthor(id);

        toastr.success("Author deleted");
    },

    render: function () {
        return (
            <div>
                <h1>Author list</h1>
                <Link to="addAuthor" className="btn btn-info">Add author</Link>
                <AuthorList authors={this.state.authors} deleteAuthor={this.deleteAuthor}/>
            </div>
        );
    }
});

module.exports = AuthorPage;